<template>
  <div class="content">
    <el-card class="msg">
      <h1>欢迎回到易买网</h1>
      <el-form
        ref="ruleFormRef"
        :model="loginForm"
        :rules="rules"
        label-width="60px"
        status-icon
        class="login_form"
      >
        <el-form-item label="账号" prop="usercode">
          <el-input v-model="loginForm.usercode" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            show-password
            v-model="loginForm.password"
          />
        </el-form-item>
        <el-form-item>
          <div class="btns">
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              登录
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { login } from "@/api/login";
import { CODE } from "@/utils/StatusCode";
import { useStore } from "vuex";

const store = useStore();
const router = useRouter();
const ruleFormRef = ref<FormInstance>();

interface RuleForm {
  usercode: string;
  password: string;
}

const loginForm = reactive<RuleForm>({
  usercode: "",
  password: "",
});
const rules = reactive<FormRules<RuleForm>>({
  usercode: [
    {
      required: true,
      message: "请输入账号名",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const res = await login({
        usercode: loginForm.usercode,
        password: loginForm.password,
      });
      if (res.code == CODE.OK) {
        ElMessage({
          message: "登陆成功",
          type: "success",
        });
        store.dispatch("updateUserInfo", res.data.user);
        localStorage.setItem("token",res.data.token);
        formEl.resetFields();
      } else {
        ElMessage({
          message: res.message,
          type: "error",
        });
      }
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
<style lang="less" scoped>
.content {
  display: flex;
  justify-content: center;
  align-items: center;
}
.msg {
  width: 600px;
  height: 280px;
  padding: 5px;
  h1 {
    font-size: 24px;
    background: #e6f5e8;
    line-height: 54px;
    color: #4c4d4b;
    padding-left: 20px;
    border-bottom: 1px solid #eaeaea;
    margin: 0;
    height: 54px;
  }
}

.login_form{
  margin-top: 20px;
}
// .btns {
//   transform: translateX(96px);
// }
</style>
